<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;
use think\exception\HttpResponseException;
use think\Response;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','thirdCode','getAccessToken', "getServiceStatusLists", "getAboutPhone", "getAreaLists", "getServiceLabelLists", "getuserphonenumber"];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $sourceUserId = $this->request->post('sourceUserId', 0);
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id, $sourceUserId);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, ["pid" => $sourceUserId]);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $sourceUserId = $this->request->post('sourceUserId', 0);
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, ["pid" => $sourceUserId]);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    //快捷登录
    public function getAccessToken(){
        // $platform = 'wechat';
        // $config = get_addon_config('third');

        // if (!$config || !isset($config[$platform])) {

        //     $this->error(__('Invalid parameters'));
        // }

        // $appid = $config[$platform]['app_id'];
        // $app_secret = $config[$platform]['app_secret'];

        // ////
        // $acc_url = "https://api.weixin.qq.com/cgi-bin/stable_token";
        // $acc_data['appid'] = $appid;
        // $acc_data['secret'] = $app_secret;
        // $acc_data['grant_type'] = "client_credential";
        // //var_dump($acc_data);
        // $acc_re_data =  Http::sendRequest($acc_url,json_encode($acc_data));
        // // var_dump($acc_re_data);exit;
        // $access_token = json_decode($acc_re_data['msg'],true);

        $access_token = $this->getWechatAccessToken();

        ///
         $re_data['access_token'] = $access_token['access_token'];
         $this->success('成功',$re_data);
    }
    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function thirdCode()
    {
        $url = url('user/index');

        $sourceUserId = $this->request->post('sourceUserId', 0);

        //以防万一，前端 傻D 非要传undefined
        if($sourceUserId == "undefined" || empty($sourceUserId)){
            $sourceUserId = 0;
        }
        $code = $this->request->post("code");
        $platform = $this->request->post("platform");
        if (!$code || !$platform) {
            $this->error('参数错误！');
        }
        //获取微信access_token
        $access_token = $this->getWechatAccessToken();
        
        //获取用户openid
        $get_open_id = $this->getOpenid($code);

        $re_data['access_token'] = $access_token['access_token'];
        $re_data["openid"] = $get_open_id["openid"];
        $third_data = Db::name("third")->where(['openid' => $get_open_id['openid']])->find();

        if ($third_data) {//直接登录
            //是否绑定了手机号
            $user_info = Db::name("user")->field("mobile")->where(['id' => $third_data['user_id']])->find();
            if(!$user_info["mobile"]){
                $this->error('未绑定手机号', $re_data);
            }
            $this->auth->direct($third_data['user_id'], $sourceUserId);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }else{//走注册流程
            $ret = $this->auth->register("微信用户_" . time(), "123123", '', "", ['openid' => $get_open_id['openid'],'session_key'=>$get_open_id['session_key'], "pid" => $sourceUserId]);

            if(!$ret){
                Db::name("log")->insert([
                    "url" => "thirdCode/微信注册失败:",
                    "log_result" =>  "". $get_open_id["openid"] . json_encode($ret, JSON_UNESCAPED_UNICODE),
                    "datetime" => date("Y-m-d H:i:s")
                ]);
                $this->error("注册失败");
            }
            
            $this->error('未绑定手机号', $re_data);
        }
    }

    //获取用户手机号+覆盖用户手机号
    public function getuserphonenumber(){
        $code = $this->request->post("code");
        $access_token = $this->request->post("access_token");
        $openid = $this->request->post("openid");

        if (!$access_token || !$code || !$openid) {
            $this->error('参数错误！');
        }
        
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;
            $acc_data['code'] = $code;
        //var_dump($acc_data);
        $acc_re_data =  Http::sendRequest($url,json_encode($acc_data));

       // var_dump($acc_re_data);
        $acc_re_data = json_decode($acc_re_data['msg'],true);

        
        try{
            $data = [];
            //记录日志
            Db::name("log")
            ->insert([
                "url" => "微信获取用户手机号",
                "log_result" => json_encode($acc_re_data, JSON_UNESCAPED_UNICODE),
                "datetime" => date("Y-m-d H:i:s")
            ]);
            //验证用户是否已经绑定了手机号
            if(isset($acc_re_data["phone_info"]['phoneNumber']) && $acc_re_data["phone_info"]['phoneNumber']){
                $phoneNumber = $acc_re_data["phone_info"]['phoneNumber'];

                //是否需要更新用户信息
                $is_update_user = true;

                //是否已注册
                $third_data = Db::name("third")->where(['openid' => $openid])->find();
                if($third_data){
                    //查重
                    $have_mobile = Db::name("user")
                    ->field("id, mobile")
                    ->where("mobile = " . $phoneNumber)
                    ->find();

                    //合并账号 并且删除微信注册的user信息
                    if($have_mobile){
                        $is_update_user = false;
                        Db::name("third")->where(['openid' => $openid])->update(["user_id" => $have_mobile["id"]]);
                        Db::name("user")->delete(["id" => $third_data["user_id"]]);
                        $third_data["user_id"] = $have_mobile["id"];
                        
                    }

                    //查询用户信息
                    $user_info = Db::name("user")->where(['id' => $third_data['user_id']])->find();
                    //查不到
                    if(!$user_info){
                        $this->error("找不到用户信息");
                    }else if($is_update_user){
                        //直接修改用户信息
                        Db::name("user")
                        ->where("id = " . $user_info["id"])
                        ->update([
                            "username" => $phoneNumber,
                            "nickname" => substr_replace($phoneNumber, '****', 3, 4),
                            "mobile" => $phoneNumber
                        ]);
                    }
                    $this->auth->direct($third_data['user_id'], 0);
                    $data = ['userinfo' => $this->auth->getUserinfo()];
                }else{
                    $this->error("找不到微信信息");
                }
            }else{
                $this->error("手机号获取失败");
            }
        }catch (\Exception $e) {
            Db::name("log")->insert([
                "log_result" => $e->getMessage() . $e->getFile() . $e->getLine(),
                "datetime" => date("Y-m-d H:i:s")
            ]);
            $this->error( $e->getMessage() . $e->getFile() . $e->getLine());
        }
        

        $this->success('登录成功', $data);
    }

    //获取用户openid
    private function getOpenid($code)
    {
        $config = get_addon_config('third');

        $platform = "wechat";
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $appid = $config[$platform]['app_id'];
        $app_secret = $config[$platform]['app_secret'];

        $post_data['appid'] = $appid;
        $post_data['secret'] = $app_secret;
        $post_data['js_code'] = $code;
        $post_data['grant_type'] = 'authorization_code';
        $url = "https://api.weixin.qq.com/sns/jscode2session";
        //$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$app_secret."&js_code=".$code."&grant_type=authorization_code";

        $get_open_id = self::curlGet($url, $post_data);
        
        $get_open_id = json_decode($get_open_id, true);

        return $get_open_id;
    }

    //获取微信access_token
    private function getWechatAccessToken()
    {
        $platform = "wechat";
        $config = get_addon_config('third');

        if (!$config || !isset($config[$platform])) {

            $this->error(__('Invalid parameters'));
        }

        $appid = $config[$platform]['app_id'];
        $app_secret = $config[$platform]['app_secret'];

        ////
        $acc_url = "https://api.weixin.qq.com/cgi-bin/stable_token";
        $acc_data['appid'] = $appid;
        $acc_data['secret'] = $app_secret;
        $acc_data['grant_type'] = "client_credential";
        //var_dump($acc_data);
       $acc_re_data =  Http::sendRequest($acc_url,json_encode($acc_data));
      // var_dump($acc_re_data);exit;
       $access_token = json_decode($acc_re_data['msg'],true);

       return $access_token;
    }

    //三方登录+注册，前提是用户信息中包含手机号
    public function third()
    {
        $url = url('user/index');
        $encryptedData = $this->request->post('encryptedData', '', 'trim');
        $iv = $this->request->post('iv');
        $sourceUserId = $this->request->post('sourceUserId', 0);
        //$iv = 'Ik+hKQ2k6uHDGd5rtB6F4Q==';
        //$encryptedData = "BvgZicH80/x1HGfu3UOXeMfCdMcdmbCGIk/YN1VB7uLkLdTLS21wgU3mj/6MgDfbFjWX/ORlTAM72rzs2zJ1ps5OWBSARZBnG5vzVwYH/Wd2Ud1xZ2awSJ3cSj0M30JpOQHsbGTwfYQtQu3WO5kD9GutE/IJa70V6YABxlNDXNUu0EszRMrK8uE10HjY3/YOqP6mhCC44Kg9ugKX/XM0BA==";
        $code = $this->request->post("code");
        $platform = $this->request->post("platform");
        if (!$encryptedData || !$iv || !$code) {
            $this->error('参数错误！');
        }
        if (strlen($iv) != 24) {
            $this->error('iv不正确！');
        }
       // $mobile = '15801127890';
        $config = get_addon_config('third');

        if (!$config || !isset($config[$platform])) {

            $this->error(__('Invalid parameters'));
        }

        $appid = $config[$platform]['app_id'];
        $app_secret = $config[$platform]['app_secret'];
        $post_data['appid'] =$appid;
        $post_data['secret'] =$app_secret;
        $post_data['js_code'] =$code;
        $post_data['grant_type'] ='authorization_code';
        $url = "https://api.weixin.qq.com/sns/jscode2session";
        //$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$app_secret."&js_code=".$code."&grant_type=authorization_code";

        $get_open_id = self::curlGet($url,$post_data);
        //var_dump($get_open_id);
        if($get_open_id){
            $get_open_id = json_decode($get_open_id,true);

            if($get_open_id['openid']){
                /*$third_data = Db::name("third")->where(['openid'=>$get_open_id['openid']])->find();
                if($third_data){//直接登录
                    $this->auth->direct($third_data['user_id']);
                    $data = ['userinfo' => $this->auth->getUserinfo()];
                    $this->success(__('Logged in successful'), $data);
                }*/
                //$json = (array)json_decode($result['msg'], true);
                $aesIV = base64_decode($iv);
                $aesCipher = base64_decode($encryptedData);
                $aesKey = base64_decode($get_open_id['session_key']);
                $re = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
                $data = json_decode($re, true);
                if ($data) {
                   // var_dump($data);exit;
                    $user = \app\common\model\User::getByMobile($data['phoneNumber']);
                    if ($user) {
                        if ($user->status != 'normal') {
                            $this->error(__('Account is locked'));
                        }
                        //如果已经有账号则直接登录
                        $ret = $this->auth->direct($user->id, $sourceUserId);
                    } else {
                        $ret = $this->auth->register($data['phoneNumber'], Random::alnum(), '', $data['phoneNumber'], ['openid'=>$get_open_id['openid'],'session_key'=>$get_open_id['session_key'], "pid" => $sourceUserId]);
                    }
                    if ($ret) {
                        //Sms::flush($data['phoneNumber'], 'mobilelogin');
                        $data = ['userinfo' => $this->auth->getUserinfo()];
                        $this->success(__('Logged in successful'), $data);
                    } else {
                        $this->error($this->auth->getError());
                    }
                }else{
                    $this->error("配置参数错误");
                }



            }else{
                $this->error("登录失败");
            }
        }else{
            $this->error("登录失败");
        }


    }
    function curlGet($url, $params = []) {
        // 初始化cURL会话
        $ch = curl_init();

        // 如果提供了参数，则构建带参数的URL
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }

        // 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将响应保存到变量而不是直接输出
        curl_setopt($ch, CURLOPT_HEADER, false); // 不返回响应头信息

        // 执行请求并获取响应
        $response = curl_exec($ch);

        // 检查请求是否成功
        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch); // 关闭cURL会话
            throw new Exception("cURL Error: " . $error);
        }

        // 关闭cURL会话
        curl_close($ch);

        // 返回响应数据
        return $response;
    }
    /*public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {

            $this->error(__('Invalid parameters'));
        }
       // var_dump($config);
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
//var_dump($result);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }*/

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    //获取用户基本信息
    public function getUserInfo()
    {
        //用户信息
        $user_info = $this->auth->getUserinfo();
        $user_info["service_labels"] = explode(",", $user_info["service_labels"]);
        $user_info["service_labels_name"] = explode(",", $user_info["service_labels_name"]);

        $this->success("操作成功", $user_info);
    }

    //获取我的足迹 1收藏 2浏览足迹
    public function getBroConLists()
    {
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);
        $type = $this->request->post("type", 0);

        if($type == 0){
            $this->error("参数缺少");
        }

        //用户信息
        $user_info = $this->auth->getUserinfo();

        //获取信息
        $lists = Db::name("consult_bro_col")
        ->where("type = " . $type)
        ->where("user_id = " . $user_info["id"])
        ->page($page, $limit)
        ->order("createtime desc")
        ->select();

        //如果是收藏的话，需要统计总数
        $count = 0;
        if($type == 1){
            $count = Db::name("consult_bro_col")
            ->where("type = " . $type)
            ->where("user_id = " . $user_info["id"])
            ->count();
        }

        if(!$lists){
           $this->success("暂无数据"); 
        }

        //数组
        $data = [];
        foreach($lists as &$value){
            if($value["createtime"]){
                $key = date("Y-m-d", $value["createtime"]);
                
                //根据咨询id，查询列表信息
                $value["image"] = "";
                $value["consult_name"] = "";
                $value["consult_createtime"] = "";
                $consult_info = Db::name("consult_manage")
                ->field("id, name, image, createtime")
                ->where("id = " . $value["consult_id"])
                ->find();
                if($consult_info){
                    $consult_info["createtime"] = date("Y-m-d H:i:s", $consult_info["createtime"]);
                    $value["image"] = $consult_info["image"];
                    $value["consult_name"] = $consult_info["name"];
                    $value["consult_createtime"] = $consult_info["createtime"];
                }
                //删除不需要的字段
                unset($value["id"]);
                unset($value["user_id"]);
                unset($value["updatetime"]);
                unset($value["deletetime"]);
                unset($value["createtime"]);
                $data[$key][] = $value;
            }
        }

        $data["count_num"] = $count;

        $this->success("操作成功", $data);
    }

    //取消收藏
    public function cancelConsult()
    {
        // $type = $this->request->post("type");
        $consult_id = $this->request->post("consult_id");
        if(!$consult_id){
            $this->error("缺少参数");
        }

        //用户信息
        $user_info = $this->auth->getUserinfo();

        //获取收藏信息
        $consult_bro_info = Db::name("consult_bro_col")
        ->where("user_id = " . $user_info["id"])
        ->where("type = 1")
        ->where("consult_id in (" . $consult_id . ")")
        ->select();

        if(!$consult_bro_info){
            $this->error("找不到收藏信息");
        }

        Db::name("consult_bro_col")
        ->where("user_id = " . $user_info["id"])
        ->where("type = 1")
        ->where("consult_id in (" . $consult_id . ")")
        ->delete();

        $this->success("取消成功");
    }

    //获取服务状态列表
    public function getServiceStatusLists()
    {
        $status = [
            [
                "id" => "all",
                "name" => "全部"
            ],
            [
                "id" => 0,
                "name" => "咨询中"
            ],
            [
                "id" => 1,
                "name" => "已成交"
            ],
            [
                "id" => 2,
                "name" => "已结束"
            ],
        ];

        $this->success("操作成功", $status);
    }

    //获取我的服务列表
    public function getMyServiceLists()
    {
        //用户信息
        $user_info = $this->auth->getUserinfo();
        $status = $this->request->post("status", "all");
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);
        $lang = $this->request->post("lang", 1);

        //区分语言
        if($lang == 1){
            $field = "
            id, 
            service_name, 
            service_banner";
        }else{
            $field = "
            id, 
            service_name_hk as service_name, 
            service_banner";
        }

        //0咨询中  1已成交   2已结束
        $statusWhere = "1 = 1";
        if($status == "all"){
            $statusWhere = "status in (0, 1, 2)";
        }else if(!empty($status)){
            $statusWhere = "status = " . $status;
        }

        //查询我申请过的服务
        $service_order_lists = Db::name("service_order")
        ->where("uid = " . $user_info["id"])
        ->where($statusWhere)
        ->page($page, $limit)
        ->select();

        if(!$service_order_lists){
            $this->success("暂未申请过服务", []);
        }

        $lists = [];

        foreach($service_order_lists as $key => $value){
            $lists[$key]["order_id"] = $value["id"];
            $lists[$key]["status"] = $value["status"];
            if($value["status"] == 0){
                $lists[$key]["status_name"] = "咨询中";
            }else if($value["status"] == 1){
                $lists[$key]["status_name"] = "已成交";
            }else if($value["status"] == 2){
                $lists[$key]["status_name"] = "已结束";
            }

            //查询服务的基本信息
            $service_info = Db::name("service")
            ->field($field)
            ->where("id = " . $value["service_id"])
            ->find();

            $lists[$key]["service_id"] = $service_info["id"];
            $lists[$key]["service_name"] = $service_info["service_name"];
            $lists[$key]["service_banner"] = $service_info["service_banner"];
            
        }
        $this->success("操作成功", $lists);

    }

    //获取我的服务详情
    public function getMyServiceDetail()
    {
        //用户信息
        $user_info = $this->auth->getUserinfo();
        $order_id = $this->request->post("order_id");

        if(!$order_id){
            $this->error("缺少必要参数");
        }

        //查询订单信息,服务信息
        $detail = Db::name("service_order")
        ->alias("o")
        ->field("o.id as order_id, o.service_id, o.schedule_json, o.contract_file, s.service_name, service_banner, service_tags, service_score")
        ->join("service s", "s.id = o.service_id", "left")
        ->where("o.uid = " . $user_info["id"])
        ->where("o.id = " . $order_id)
        ->find();

        if(!$detail){
            $this->error("暂无订单信息");
        }
        //处理数据
        $detail["schedule"] = json_decode($detail["schedule_json"], true);

        $detail["contract_file_name"] = "";
        if($detail["contract_file"]){
            $detail["contract_file_name"] = Db::name("attachment")->where("url = '" . $detail["contract_file"] . "'")->find()["filename"] ?? "";
        }

        $this->success("操作成功", $detail);
    }

    //获取我的申请信息
    public function getMyApplyDetail()
    {
        //用户信息
        $user_info = $this->auth->getUserinfo();
        $order_id = $this->request->post("order_id");

        //获取订单详情
        $order_info = Db::name("service_order")
        ->where("uid = " . $user_info["id"])
        ->where("id = " . $order_id)
        ->find();

        if(!$order_info){
            $this->error("暂无订单信息");
        }

        //查询申请的服务信息
        $service_apply_info = Db::name("service_apply")
        ->where("uid = " . $user_info["id"])
        ->where("id = " . $order_info["apply_id"])
        ->find();

        if(!$service_apply_info){
            $this->error("暂无详细信息");
        }

        //处理json数据
        if($service_apply_info["question_answer_json"]){
            $service_apply_info["question_answer_json"] = json_decode($service_apply_info["question_answer_json"], true);
        }

        $this->success("操作成功", $service_apply_info);

    }

    //根据用户获取上级销售/代理商/分公司
    public function getSaleAgentBranch($uid = 0)
    {
        $sale_uid = 0;
        $agent_uid = 0;
        $branch_office_uid = 0;

        $sale_info = Db::name("user")
        ->field("pid")
        ->where("id = " . $uid)
        ->find();

        if($sale_info["pid"] == 0){
            return ["sale_uid" => $sale_uid, "agent_uid" => $agent_uid, "branch_office_uid" => $branch_office_uid];
        }
        //判断是否为销售
        $is_sale_info = Db::name("user")
        ->field("user_type")
        ->where("id = " . $sale_info["pid"])
        ->find();
        
        if($is_sale_info["user_type"] == 3){
            $sale_uid = $sale_info["pid"];

            $agent_info = Db::name("user")
            ->field("pid")
            ->where("id = " . $sale_uid)
            ->find();
            //判断是否为代理商
            $is_agent_info = Db::name("user")
            ->field("user_type")
            ->where("id = " . $agent_info["pid"])
            ->find();
            if($is_agent_info["user_type"] == 2){
                $agent_uid = $agent_info["pid"];
                
                $branch_office_info = Db::name("user")
                ->field("pid")
                ->where("id = " . $agent_uid)
                ->find();
                //判断是否为分公司
                $is_branch_info = Db::name("user")
                ->field("user_type")
                ->where("id = " . $branch_office_info["pid"])
                ->find();
                if($is_branch_info["user_type"] == 1){
                    $branch_office_uid = $branch_office_info["pid"];
    
                }
            }
        }

        return ["sale_uid" => $sale_uid, "agent_uid" => $agent_uid, "branch_office_uid" => $branch_office_uid];
        
    }

    //获取附加菜单
    public function getUserMenu()
    {
        $user_info = $this->auth->getUserinfo();
        //判断角色 0客户 1分公司  2代理商  3销售
        if($user_info["user_type"] == 0){
            $this->success("操作成功");
        }else if($user_info["user_type"] == 1){
            $this->success("操作成功", ["menu" => "进入分公司", "type" => 1]);
        }else if($user_info["user_type"] == 2){
            $this->success("操作成功", ["menu" => "进入代理商", "type" => 2]);
        }else if($user_info["user_type"] == 3){
            $this->success("操作成功", ["menu" => "进入销售", "type" => 3]);
        }
    }

    //客服热线
    public function getAboutPhone()
    {
        //获取后台的配置
        $config = Db::name("config")
        ->where("name = 'phone'")
        ->find();
        $this->success("操作成功", ["phone_number" => $config["value"]]);
    }

    //修改我的基本信息（区别于系统自带的修改）
    public function editUserInfo()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $province_id = $this->request->post('province_id', 0);
        $city_id = $this->request->post('city_id', 0);
        $district_id = $this->request->post('district_id', 0);
        $address = $this->request->post('address', "");
        $mobile = $this->request->post('mobile', 0);
        
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }

        if ($mobile) {
            $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error("手机号已被注册");
            }
            $user->mobile = $mobile;
        }

        $user->province_id = $province_id;
        $user->city_id = $city_id;
        $user->district_id = $district_id;
        $user->address = $address;

        $user->save();
        $this->success("修改成功");
    }

    //获取省市县三级联动数据
    public function getAreaLists()
    {
        $province = $this->request->post('province_id', 0);
        $city = $this->request->post('city_id', 0);

        $where = ['pid' => 0, 'level' => 1];
        $provincelist = [];
        if ($province != 0) {
            $where['pid'] = $province;
            $where['level'] = 2;
            if ($city != 0) {
                $where['pid'] = $city;
                $where['level'] = 3;
            }
        }
        $provincelist = Db::name('area_new')->where($where)->field('id, name')->select();
        $this->success('操作成功', $provincelist);
    }

    //进入分公司、代理商、销售个人主页   1分公司  2代理商  3销售
    public function getSaleAgentBranchDetail()
    {
        $type = $this->request->post('type', 0);

        if($type == 0){
            $this->error("参数错误");
        }

        //获取用户信息
        $user_info = $this->auth->getUserinfo();
        //判断当前用户的角色查询数据
        if($type == 1){
            $where = "branch_office_uid = " . $user_info["id"];
            $sum = "branch_office_money";
        }else if($type == 2){
            $where = "agent_uid = " . $user_info["id"];
            $sum = "agent_money";
        }else if($type == 3){
            $where = "sale_uid = " . $user_info["id"];
            $sum = "sale_money";
        }

        //我的订单数量
        $order_count = Db::name("service_order")
        ->where($where)
        ->count();
        $user_info["order_count"] = $order_count ?? 0;
        
        //我的分红金额
        $order_commission_money = Db::name("service_order")
        ->where($where)
        ->sum($sum);
        $user_info["order_commission_money"] = $order_commission_money ?? 0;

        //我的代理商数量，只有分公司可以看到
        $agent_lists = $this->getUserCountTotal($type, $user_info["id"])["agent_lists"];
        $user_info["agent_count"] = count($agent_lists) ?? 0;

        //我的销售数量，只有代理商和分公司可以看到
        $sale_lists = $this->getUserCountTotal($type, $user_info["id"])["sale_lists"];
        $user_info["sale_count"] = count($sale_lists) ?? 0;

        //我的客户数量，查询实时数量，不查订单,三个角色都可以看到
        $user_lists = $this->getUserCountTotal($type, $user_info["id"])["user_lists"];
        $user_info["user_count"] = count($user_lists) ?? 0;

        $this->success("操作成功", $user_info);
        
    }

    //获取对应角色的下级客户数组
    public function getUserCountTotal($type, $uid)
    {
        $data = [];
        //代理商数组
        $data["agent_lists"] = [];
        //销售数组
        $data["sale_lists"] = [];
        //客户数组
        $data["user_lists"] = [];

        // 1分公司  2代理商  3销售
        if($type == 1){
            //代理商数组
            $agent_one_array = $this->getNextUserLists(explode(",", $uid));
            if(!$agent_one_array){
                return $data;
            }
            $data["agent_lists"] = $agent_one_array;

            //销售数组
            $sale_one_array = $this->getNextUserLists($agent_one_array);
            if(!$sale_one_array){
                return $data;
            }
            $data["sale_lists"] = $sale_one_array;

            //客户数组
            $user_one_lists = $this->getNextUserLists($sale_one_array);
            if(!$user_one_lists){
                return $data;
            }
            $data["user_lists"] = $user_one_lists;
        }else if($type == 2){
            //销售数组
            $sale_one_array = $this->getNextUserLists(explode(",", $uid));
            if(!$sale_one_array){
                return $data;
            }
            $data["sale_lists"] = $sale_one_array;

            //客户数组
            $user_one_lists = $this->getNextUserLists($sale_one_array);
            if(!$user_one_lists){
                return $data;
            }
            $data["user_lists"] = $user_one_lists;
        }else if($type == 3){
            //客户数组
            $user_one_lists = $this->getNextUserLists(explode(",", $uid));
            if(!$user_one_lists){
                return $data;
            }
            $data["user_lists"] = $user_one_lists;
        }
        return $data;
    }

    //获取下一级用户
    private function getNextUserLists(array $uid)
    {
        //二维数组
        $user_two_array = Db::name("user")
        ->field("id")
        ->where("pid in (" . implode(",", $uid) . ")")
        ->select();

        if(!$user_two_array){
            return false;
        }
        //返回一维数组
        return array_column($user_two_array, "id");
    }

    //我的所有客户订单列表
    public function getMyOrderLists()
    {
        $type = $this->request->post('type', 0);
        $status = $this->request->post('status', "all");
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);

        if($type == 0){
            $this->error("参数错误");
        }

        //0咨询中  1已成交   2已结束
        $statusWhere = "1 = 1";
        if($status == "all"){
            $statusWhere = "status in (0, 1, 2)";
        }else if(!empty($status) || $status == "0"){
            $statusWhere = "status = " . $status;
        }

        //获取用户信息
        $user_info = $this->auth->getUserinfo();
        //判断当前用户的角色查询数据
        if($type == 1){
            $where = "branch_office_uid = " . $user_info["id"];
        }else if($type == 2){
            $where = "agent_uid = " . $user_info["id"];
        }else if($type == 3){
            $where = "sale_uid = " . $user_info["id"];
        }
        $order_lists = Db::name("service_order")
        ->where($where)
        ->where($statusWhere)
        ->page($page, $limit)
        ->select();

        if(!$order_lists){
            $this->success("暂无订单", []);
        }

        foreach($order_lists as &$val){
            if($val["status"] == 0){
                $val["status_name"] = "咨询中";
            }else if($val["status"] == 1){
                $val["status_name"] = "已成交";
            }else if($val["status"] == 2){
                $val["status_name"] = "已结束";
            }

            $val["createtime"] = date("Y-m-d H:i:s", $val["createtime"]);

            $val["service_img"] = trim($val["service_img"], "/");

            $order_user_info = Db::name("user")
            ->field("mobile, nickname")
            ->where("id = " . $val["uid"])
            ->find();

            $val["mobile"] = $order_user_info["mobile"];
            $val["nickname"] = $order_user_info["nickname"];
        }

        $this->success("操作成功", $order_lists);
    }

    //我的客户订单详情
    public function getMyOrderDetail()
    {
        //获取用户信息
        $user_info = $this->auth->getUserinfo();
        $order_id = $this->request->post('order_id', 0);
        $type = $this->request->post('type', 0);
        
        if($order_id == 0 || $type == 0){
            $this->error("缺少必要参数");
        }
        
        if($type == 1){
            $field = ", branch_office_money as my_money";
        }else if($type == 2){
            $field = ", agent_money as my_money";
        }else if($type == 3){
            $field = ", sale_money as my_money";
        }

        //获取订单信息
        $order_info = Db::name("service_order")
        ->field("id, order_no, uid, service_id, createtime, order_money" . $field)
        ->where("id = " . $order_id)
        ->find();

        if(!$order_info){
            $this->error("找不到订单信息");
        }

        //服务信息
        $order_info["service_info"] = Db::name("service")
        ->where("id = " . $order_info["service_id"])
        ->find() ?? [];

        $order_info["service_info"]["service_where"] = array_values(json_decode($order_info["service_info"]["service_where"], true));
        
        $order_info["service_info"]["material"] = array_values(json_decode($order_info["service_info"]["material"], true));
        
        $order_info["createtime"] = date("Y-m-d H:i:s", $order_info["createtime"]);

        //下单人信息
        $order_user_info = Db::name("user")
        ->where("id = " . $order_info["uid"])
        ->find();
        $order_info["user_nickname"] = $order_user_info["nickname"];
        $order_info["user_mobile"] = $order_user_info["mobile"];
        $order_info["user_address"] = $order_user_info["address"];

        $this->success("操作成功", $order_info);
    }

    //客户管理（我的客户）
    public function getMyUserLists()
    {
        $type = $this->request->post('type', 0);
        $search = $this->request->post('search', "");
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);

        $where = "1=1";
        if(!empty($search)){
            $where = "nickname like '%" . $search . "%'";
        }

        //获取用户信息
        $user_info = $this->auth->getUserinfo();

        //查询我的所有客户
        $user_array = $this->getUserCountTotal($type, $user_info["id"])["user_lists"];

        if(count($user_array) == 0){
            $this->success("暂无客户", []);
        }

        $user_lists = Db::name("user")
        ->where($where)
        ->where("id in (" . implode(",", $user_array) . ")")
        ->page($page, $limit)
        ->select();

        foreach($user_lists as &$value){
            $value["service_labels"] = $value["service_labels"] ? explode(",", $value["service_labels"]) : [];
            $value["service_labels_name"] = $value["service_labels_name"] ? explode(",", $value["service_labels_name"]) : [];
            $value["avatar"] = $value["avatar"] ? cdnurl($value["avatar"], true) : letter_avatar($value["nickname"]);
        }

        $this->success("操作成功", $user_lists);
    }

    //获取客户详情
    public function getMyUserDetail()
    {
        $uid = $this->request->post("uid", 0);

        if($uid == 0){
            $this->error("缺少必要参数");
        }

        $user_info = Db::name("user")
        ->where("id = " . $uid)
        ->find();

        $user_info["service_labels"] = $user_info["service_labels"] ? explode(",", $user_info["service_labels"]) : [];
        $user_info["service_labels_name"] = $user_info["service_labels_name"] ? explode(",", $user_info["service_labels_name"]) : [];

        $this->success("操作成功", $user_info);
    }

    //获取所有服务标签
    public function getServiceLabelLists()
    {
        $lists = Db::name("service")
        ->field("id, service_name")
        ->select();

        $this->success("操作成功", $lists);
    }

    //编辑客户资料
    public function editMyUserInfo()
    {
        $uid = $this->request->post('uid', 0);
        $nickname = $this->request->post('nickname');
        $province_id = $this->request->post('province_id', 0);
        $city_id = $this->request->post('city_id', 0);
        $district_id = $this->request->post('district_id', 0);
        $address = $this->request->post('address', "");
        $mobile = $this->request->post('mobile', 0);
        $service_labels = $this->request->post('service_labels', "");
        $service_labels_name = $this->request->post('service_labels_name', "");
        
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $uid)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
        }

        if ($mobile) {
            $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $uid)->find();
            if ($exists) {
                $this->error("手机号已被注册");
            }
        }

        Db::name("user")
        ->where("id = " . $uid)
        ->update([
            "nickname" => $nickname,
            "province_id" => $province_id,
            "city_id" =>$city_id,
            "district_id" => $district_id,
            "address" => $address,
            "mobile" => $mobile,
            "service_labels" => $service_labels,
            "service_labels_name" => $service_labels_name
        ]);
        $this->success("修改成功", []);
    }

    //我的分红
    public function getMyOrderMoneyLists()
    {
        //获取用户信息
        $user_info = $this->auth->getUserinfo();
        $order_no = $this->request->post("order_no", "");
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);
        $type = $this->request->post('type', 0);
        if($type == 0){
            $this->error("缺少必要参数");
        }

        $where = "1=1";
        if(!empty($order_no)){
            $where .= " and order_no like '%" . $order_no . "%'";
        }

        if($type == 1){
            $where .= " and branch_office_uid = " . $user_info["id"];
            $field = ", branch_office_money as my_money";
        }else if($type == 2){
            $where .= " and agent_uid = " . $user_info["id"];
            $field = ", agent_money as my_money";
        }else if($type == 3){
            $where .= " and sale_uid = " . $user_info["id"];
            $field = ", sale_money as my_money";
        }

        $lists = Db::name("service_order")
        ->field("id, order_no, createtime" . $field)
        ->where($where)
        ->page($page, $limit)
        ->select();

        if(!$lists){
            $this->success("暂无订单", []);
        }

        foreach($lists as &$value){
            $value["createtime"] = date("Y-m-d H:i:s", $value["createtime"]);
        }

        $this->success("操作成功", $lists);
        
    }

    //获取我的代理商（仅分公司可以看到）
    public function getMyAgentLists()
    {
        //获取用户信息
        $user_info = $this->auth->getUserinfo();
        if($user_info["user_type"] != 1){
            $this->error("您还不是分公司角色，无法看到代理商数据", []);
        }
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);
        $agent_name = $this->request->post("agent_name", 10);

        //获取我的下级所有代理商
        $agent_array = $this->getUserCountTotal(1, $user_info["id"])["agent_lists"];
        if(count($agent_array) == 0){
            $this->success("暂无代理");
        }

        $where = "1=1";
        if(!empty($agent_name)){
            $where = "user_type_name like '%" . $agent_name . "%'";
        }

        //统计代理商数据
        $agent_lists = Db::name("user")
        ->where("id in (" . implode(",", $agent_array) . ")")
        ->where($where)
        ->page($page, $limit)
        ->select();

        if(!$agent_lists){
            $this->success("暂无代理", []);
        }

        foreach($agent_lists as &$value){
            //获取代理商销售人员数量
            $sale_array = $this->getUserCountTotal(2, $value["id"])["sale_lists"];
            $value["sale_num"] = count($sale_array) ?? 0;
            $value["avatar"] = $value["avatar"] ? cdnurl($value["avatar"], true) : letter_avatar($value["nickname"]);

            //获取代理涉及的订单数量
            $value["order_num"] = Db::name("service_order")
            ->where("agent_uid = " . $value["id"])
            ->count();

            //获取成交金额
            $value["order_money"] = Db::name("service_order")
            ->where("agent_uid = " . $value["id"])
            ->sum("order_money");

            //获取分红金额
            $value["agent_money"] = Db::name("service_order")
            ->where("agent_uid = " . $value["id"])
            ->sum("agent_money");
        }

        $this->success("操作成功", $agent_lists);
    }

    //代理商详情
    public function getMyAgentDetail()
    {
        $agent_id = $this->request->post("agent_id", 0);

        $agent_info = Db::name("user")
        ->field("id, user_type_name, username, nickname, mobile, full_address")
        ->where("id = " . $agent_id)
        ->find();

        $this->success("操作成功", $agent_info);
    }

    //添加/编辑代理商信息
    public function saveMyAgentInfo()
    {
        $agent_id = $this->request->post('agent_id', 0);
        $user_type_name = $this->request->post('user_type_name');
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $nickname = $this->request->post('nickname');
        $mobile = $this->request->post('mobile', 0);
        $full_address = $this->request->post('full_address', "");
        
        if ($user_type_name) {
            $exists = \app\common\model\User::where('user_type_name', $user_type_name)->where('id', '<>', $agent_id)->find();
            if ($exists) {
                $this->error("代理商名称已被注册");
            }
        }

        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $agent_id)->find();
            if ($exists) {
                $this->error("账号已被注册");
            }
        }

        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $agent_id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
        }

        if ($mobile) {
            $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $agent_id)->find();
            if ($exists) {
                $this->error("手机号已被注册");
            }
        }

        if($agent_id != 0){
            $agent_info = Db::name("user")
            ->where("id = " . $agent_id)
            ->find();

            Db::name("user")
            ->where("id = " . $agent_id)
            ->update([
                "nickname" => $nickname,
                "user_type_name" => $user_type_name,
                "username" => $username,
                "password" => !empty($password) ? md5(md5($password) . $agent_info["salt"]) : $agent_info["password"],
                "mobile" => $mobile,
                "full_address" => $full_address
            ]);
        }else{
            $salt = Random::alnum();

            if(empty($password)){
                $this->error("请输入密码");
            }

            Db::name("user")
            ->where("id = " . $agent_id)
            ->insert([
                "nickname" => $nickname,
                "pid" => $this->auth->id,
                "user_type" => 2,
                "user_type_name" => $user_type_name,
                "username" => $username,
                "password" => md5(md5($password) . $salt),
                "salt" => $salt,
                "mobile" => $mobile,
                "status" => "normal",
                "full_address" => $full_address,
                "createtime" => time()
            ]);
        }
        
        $this->success("操作成功");
    }

    //我的销售管理列表
    public function getMySaleLists()
    {
        //获取用户信息
        $user_info = $this->auth->getUserinfo();
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);
        $type = $this->request->post("type", 0);

        if(!$type){
            $this->error("缺少必要参数");
        }

        //获取我的下级所有销售
        $sale_array = $this->getUserCountTotal($type, $user_info["id"])["sale_lists"];
        if(count($sale_array) == 0){
            $this->success("暂无销售人员");
        }

        //统计销售数据
        $sale_lists = Db::name("user")
        ->where("id in (" . implode(",", $sale_array) . ")")
        ->page($page, $limit)
        ->select();

        if(!$sale_lists){
            $this->success("暂无销售人员", []);
        }

        foreach($sale_lists as &$value){
            //获取销售涉及的订单数量
            $value["order_num"] = Db::name("service_order")
            ->where("sale_uid = " . $value["id"])
            ->count();

            //获取成交金额
            $value["order_money"] = Db::name("service_order")
            ->where("sale_uid = " . $value["id"])
            ->sum("order_money");

            $value["avatar"] = $value["avatar"] ? cdnurl($value["avatar"], true) : letter_avatar($value["nickname"]);

        }

        $this->success("操作成功", $sale_lists);
    }

    //销售详情
    public function getMySaleDetail()
    {
        $sale_id = $this->request->post("sale_id", 0);

        $agent_info = Db::name("user")
        ->field("id, username, desc, nickname, mobile, full_address")
        ->where("id = " . $sale_id)
        ->find();

        $this->success("操作成功", $agent_info);
    }

    //添加/编辑销售人员信息
    public function saveMySaleInfo()
    {
        $sale_id = $this->request->post('sale_id', 0);
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $nickname = $this->request->post('nickname');
        $desc = $this->request->post('desc', "");
        $mobile = $this->request->post('mobile', 0);
        $full_address = $this->request->post('full_address', "");

        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $sale_id)->find();
            if ($exists) {
                $this->error("账号已被注册");
            }
        }

        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $sale_id)->find();
            if ($exists) {
                $this->error(__('联系人已存在，请更换后重试'));
            }
        }

        if ($mobile) {
            $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $sale_id)->find();
            if ($exists) {
                $this->error("手机号已被注册");
            }
        }

        if($sale_id != 0){
            $sale_info = Db::name("user")
            ->where("id = " . $sale_id)
            ->find();

            Db::name("user")
            ->where("id = " . $sale_id)
            ->update([
                "nickname" => $nickname,
                "username" => $username,
                "desc" => $desc,
                "password" => !empty($password) ? md5(md5($password) . $sale_info["salt"]) : $sale_info["password"],
                "mobile" => $mobile,
                "full_address" => $full_address
            ]);
        }else{
            //获取用户信息
            $user_info = $this->auth->getUserinfo();
            if($user_info["user_type"] != 2){
                $this->error("您不是代理商，无法新增销售人员");
            }
            
            if(empty($password)){
                $this->error("请输入密码", []);
            }
            $salt = Random::alnum();

            Db::name("user")
            ->where("id = " . $sale_id)
            ->insert([
                "nickname" => $nickname,
                "pid" => $this->auth->id,
                "user_type" => 3,
                "desc" => $desc,
                "username" => $username,
                "password" => md5(md5($password) . $salt),
                "salt" => $salt,
                "mobile" => $mobile,
                "status" => "normal",
                "full_address" => $full_address,
                "createtime" => time()
            ]);
        }
        
        $this->success("操作成功");
    }

    //获取我的名片（销售）
    public function getMyCard()
    {
        //获取用户信息
        $user_info = $this->auth->getUserinfo();

        if($user_info["user_type"] != 3){
            $this->error("您还不是销售，暂无名片信息");
        }

        //获取推广二维码
        $config = get_addon_config('qrcode');
        if (isset($config['limitreferer']) && $config['limitreferer']) {
            $referer = $this->request->server('HTTP_REFERER', '');
            $refererInfo = parse_url($referer);
            $refererHost = $referer && $refererInfo ? $refererInfo['host'] : '';
            $refererHostArr = explode('.', $refererHost);
            $wildcardDomain = '';
            if (count($refererHostArr) > 2) {
                $refererHostArr[0] = '*';
                $wildcardDomain = implode('.', $refererHostArr);
            }
            $allowRefererList = $config['allowrefererlist'] ?? '';
            $domainArr = explode("\n", str_replace("\r", "", $allowRefererList));
            $domainArr = array_filter(array_unique($domainArr));
            $domainArr[] = request()->host(true);

            $inAllowList = false;

            if (in_array('*', $domainArr) || ($refererHost && in_array($refererHost, $domainArr)) || ($wildcardDomain && in_array($wildcardDomain, $domainArr))) {
                $inAllowList = true;
            }

            if (!$inAllowList && (!$referer && $config['allowemptyreferer'])) {
                $inAllowList = true;
            }

            if (!$inAllowList) {
                $response = Response::create('暂无权限', 'html', 403);
                throw new HttpResponseException($response);
            }
        }

        $host_config = Db::name("config")
        ->where("name = 'url'")
        ->find();
        $params["text"] = $host_config["value"] . "/?sourceUserId=" . $user_info["id"];
        
        $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));

        $qrCode = \addons\qrcode\library\Service::qrcode($params);

        // 写入到文件
        if ($config['writefile']) {
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $fileName = md5(implode('', $params)) . '.' . $config['format'];
                $filePath = $qrcodePath . $fileName;
                $fileUrl = "/uploads/qrcode/" . $fileName;
                $user_info["qrcode"] = $fileUrl;
                $qrCode->writeFile($filePath);
            }
        }

        $this->success("操作成功", $user_info);
    }
}
